<?php
/*
 * Shopping cart
 * @author: Trieu
 * */

class cart{

	function &instance(){
		static $cart;
		if (empty($cart)){
			$cart = new cart();
		}
		return $cart;
	}

	/*
	 * Add shopping cart
	 * */
	function addShoppingCart($array = array()){
		global $_G;
		$status = true;

		if (!$_G['uid'] || !is_array($array))
			$status = false;

		if ($status == true){
			if (cart::checkPID($array['pid'], $array['uid'])){
				$pArray = cart::proInfo($array['pid']);

				if (!empty($pArray)){
					if ($array['quantity'] > 1)
						$cost = $pArray[0]['end_price']*$array['quantity'];
					elseif ($array['quantity'] == 1)
						$cost = $pArray[0]['end_price'];

					DB::query('UPDATE ' . DB::table('shop_cart') . '
								SET quantity = quantity + ' . $array['quantity'] . ', price = ' . $pArray[0]['end_price'] . ', cost = cost + ' . $cost . ', dateline = ' . TIMESTAMP . '
								WHERE uid = ' . $array['uid'] . ' AND pid = ' . $array['pid'] . ' AND sid = ' . $array['sid']);
				}
			}else{
				$pArray = cart::proInfo($array['pid']);

				if (!empty($pArray)){
					$arr = array(
							'sid'=>$array['sid'],
							'uid'=>$array['uid'],
							'pid'=>$array['pid'],
							'quantity'=>$array['quantity'],
							'price'=>$pArray[0]['end_price'],
							'cost'=>$pArray[0]['end_price'] * $array['quantity'],
							'dateline'=>TIMESTAMP
					);
					DB::insert('shop_cart', $arr);
				}
			}
		}

		return $status;
	}

	function checkPID($pid, $uid){
		$Qry = 'SELECT uid
				FROM ' . DB::table('shop_cart') . '
				WHERE uid = ' . $uid . ' AND pid = ' . $pid;

		$res = DB::result_first($Qry);

		return $res;
	}

	/*
	 * Check product exists
	 * */
	function productExists($pid){
		$Qry = 'SELECT pid
				FROM ' . DB::table('shop_products') . '
				WHERE hide = 0 AND available = 1 AND status = 1 AND pid = ' . $pid;

		$res = DB::result_first($Qry);

		return $res;
	}

	/*
	 * Product info
	 * */
	function proInfo($pid){
		global $_G;
		$array = array();

		$Qry = 'SELECT pprice, sales, status
				FROM ' . DB::table('shop_products') . '
				WHERE hide = 0 AND available = 1 AND pid = ' . $pid;

		$res = DB::query($Qry);

		while ($row = DB::fetch($res)){
			if ($row['sales'] > 0 && $row['status'] == 1)
				$row['end_price'] = round($row['pprice'] - (($row['pprice'] * $row['sales']) / 100));
			else
				$row['end_price'] = $row['pprice'];

			$array[] = $row;
		}

		return $array;
	}

	/*
	 * Delete item
	 * */
	function deleteItem($pid, $sid){
		global $_G;
		$status = true;

		if (!$_G['uid'] || !$pid)
			$status = false;

		if (cart::checkPID($pid, $_G['uid'])){
			$condition = 'uid = ' . $_G['uid'] . ' AND pid = ' . $pid . ' AND sid = ' . $sid;

			DB::delete('shop_cart', $condition);
		}

		return $status;
	}

	/*
	 * Delete cart
	 * */
	function deleteCart($sid){
		global $_G;
		$status = true;

		if (!$_G['uid'] || !$sid)
			$status = false;

		$Qry = 'SELECT pid
				FROM ' . DB::table('shop_cart') . '
				WHERE uid = ' . $_G['uid'] . ' AND sid = ' . $sid;

		$res = DB::query($Qry);

		while ($row = DB::fetch($res)){
			cart::deleteItem($row['pid'], $sid);
		}

		return $status;
	}

	/*
	 * Get all itemts in cart
	 * return array();
	 * */
	function listCart($sid = 0){
		global $_G;
		$array = array();
		$mysql = '';

		if ($sid)
			$mysql = ' AND c.sid = ' . $sid;

		$Qry = 'SELECT c.*, f.shopname, p.pid, p.pname, p.img_cover, a.attachment, a.remote, p.quantity AS pquantity
				FROM ' . DB::table('shop_cart') . ' c
				LEFT JOIN ' . DB::table('shop_profile') . ' f ON (c.sid = f.uid)
				LEFT JOIN ' . DB::table('shop_products') . ' p ON (c.pid = p.pid)
				LEFT JOIN ' . DB::table('shop_products_attachment') . ' a ON (p.img_cover = a.aid)
				WHERE c.uid = ' . $_G['uid'] . $mysql . '
				ORDER BY c.sid ASC, c.dateline DESC';

		$res = DB::query($Qry);

		while ($row = DB::fetch($res)){
			$row['image'] = ($row['remote'] ? $_G['setting']['ftp']['attachurl'] : $_G['setting']['attachurl']) . 'shop/' . substr($row['attachment'], 0, 10) . $row['img_cover'] . '.thumb.jpg';

			$row['pprice'] = FormatNumber($row['price']);
			$row['totalCost'] = FormatNumber($row['cost']);

			$array[] = $row;
		}

		return $array;
	}

	/*
	 * recount price of item
	 * return int number
	 * */
	function recountPrice($pid, $q = 1){
		global $_G;
		$count = 0;

		$pArray = cart::proInfo($pid);

		if ($q){
			$quantity = $q;
			$cost = $pArray[0]['end_price']*$q;
		}

		$update = 'UPDATE ' . DB::table('shop_cart') . '
					SET quantity = ' . $quantity . ', cost = ' . $cost . ', dateline = ' . TIMESTAMP . '
					WHERE uid = ' . $_G['uid'] . ' AND pid = ' . $pid;

		DB::query($update);

		$Qry = 'SELECT cost
				FROM ' . DB::table('shop_cart') . '
				WHERE uid = ' . $_G['uid'] . ' AND pid = ' . $pid;

		$count = DB::result_first($Qry);
		$count = FormatNumber($count);

		return $count;
	}

	/*
	 * recount totla of bill
	 * return number
	 * */
	function recountBill($sid){
		global $_G;
		$count = '';

		$Qry = 'SELECT SUM(cost) AS OrderTotal
				FROM ' . DB::table('shop_cart') . '
				WHERE uid = ' . $_G['uid'] . ' AND sid = ' . $sid;

		$res = DB::query($Qry);

		while ($row = DB::fetch($res)){
			$count = FormatNumber($row['OrderTotal']);
		}

		return $count;
	}

	/*
	 * Total itemts in cart
	 * return int number
	 * */
	function totalitemts(){
		global $_G;
		$count = 0;

		$count = getcount('shop_cart', 'uid=' . $_G['uid']);

		return $count;
	}

	/*
	 * Total items in bill
	 * return number
	 * */
	function totalBill($sid){
		global $_G;
		$count = 0;

		$count = getcount('shop_cart', 'sid = ' . $sid . ' AND uid=' . $_G['uid']);

		return $count;
	}

	/*
	 * insert bill
	 * */
	function insertBill($sid, $info = array(), $bill = array(), $money = ''){
		global $_G;

		if (!$_G['uid'] || empty($bill) || empty($info))
			return false;

		$billCode = 'Bill-' . createRandomCode();

		$saler = array(
				'code'=>$billCode,
				'idtype'=>'saler',
				'dateline'=>TIMESTAMP,
				'bill'=>$bill,
				'totalprice'=>$money
		);
		$forsaler = array_merge($saler, $info);

		$forbuyer = array(
				'uid'=>intval($_G['uid']),
				'code'=>$billCode,
				'idtype'=>'buyer',
				'dateline'=>TIMESTAMP,
				'bill'=>$bill,
				'note'=>$info['note'],
				'totalprice'=>$money
		);

		$bid = DB::insert('shop_bill', $forbuyer);
		$sal = DB::insert('shop_bill', $forsaler, true);

		if ($bid && $sal){
			cart::delAll($sid);

			/*
			 * Notice and send mail to saler
			 * */
			$array = array(
					'actor'=>$_G['uid'],
					'code'=>$billCode,
					'url'=>'shop.php?mod=store&ac=bill&bid=' . $sal,
			);
			notification_add($sid, 'orderproduct', 'your_new_order', $array, 1);

			// Send mail
//			include libfile('function/mail');

//			$toemail = cart::mailSaler($sid);
//			$subject = lang('shop/template', 'ban_co_don_hang_moi');
//			$message = lang('shop/template', 'noi_dung_don_hang');

//			sendmail($toemail, $subject, $message);

			return true;
		}
	}

	/*
	 * email saler
	 * for send mail
	 * */
	function mailSaler($uid){
		$email = '';

		$Qry = 'SELECT email
				FROM ' . DB::table('common_member') . '
				WHERE uid = ' . $uid;

		$email = DB::result_first($Qry);

		return $email;
	}

	/*
	 * Delete cart after send bill
	 * */
	function delAll($sid){
		global $_G;

		if (!$_G['uid'])
			return false;

		$condition = 'uid = ' . $_G['uid'] . ' AND sid = ' . $sid;
		DB::delete('shop_cart', $condition);
	}
}